package cn.xiaobai.knife4j.spring.boot.factory;

import lombok.SneakyThrows;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * 自定义配置文件参数
 * @author yangdaji
 */
public class CommPropertySourceFactory implements PropertySourceFactory {


    /**
     * 通过PropertySource注解获取配置文件中的参数值,注入对象属性
     *
     * @param name     name
     * @param resource resource
     * @return
     * @throws IOException
     */
    @SneakyThrows
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) {
        String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        assert resourceName != null;
        if (!resourceName.endsWith(".yml") && !resourceName.endsWith(".yaml")) {
            return new DefaultPropertySourceFactory().createPropertySource(name, resource);
        } else {
            List<PropertySource<?>> load = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
            return load.get(0);
        }
    }
}
